#include "map.h"

Map::Map(const string& filename) {
  is_loaded_ = loadFromFile(filename);
}

bool Map::loadFromFile(const string& filename) {
  string line;
  int rows_added = 0;
  ifstream input_file(filename.c_str());

  if (!input_file.is_open()) return false;

  while (input_file.good()) {
    getline(input_file, line);
    rows_added += addLineToMap(line);
  }
  input_file.close();

  if (rows_added <= 0) return false;
  else return true;
}

void Map::display(WINDOW *w) const {
  vector<vector<Cell> >::const_iterator row;
  int x = 0, y = 0;

  for (row = data_.begin(); row != data_.end(); ++row) {
    vector<Cell>::const_iterator cell;
    x = 0;
    for (cell = row->begin(); cell != row->end(); ++cell)
      mvwaddch(w, y, x++, *cell);
    ++y;
  }
  wrefresh(w);
}

int Map::addLineToMap(const string& line) {
  string::const_iterator it = line.begin();
  int rows_added = 0;

  while (it != line.end()) {
    vector<Cell> row;
    while (row.size() <= MAX_ROW_WIDTH && it != line.end()) {
      row.push_back(Cell(*it));
      ++it;
    }
    data_.push_back(row);
    ++rows_added;
  }

  return rows_added;
}

int Map::width() const {
  return MAX_ROW_WIDTH;
}

int Map::height() const {
  return LINES - 1;
}

bool Map::inCollision(const Character* c) const {
  if (data_.size() < c->yPos()) return false;
  vector<Cell> row = data_[c->yPos()];

  // If it's to the right of the end of a line
  if (row.size() <= c->xPos()) return false;

  // If it's on a space
  if (row[c->xPos()] == ' ') return false;
  if (row[c->xPos()] == c->appearance()) return false;
  return true;
}
